<template>
  <div class="demand-container">
    <el-card class="demand-card">
      <!-- 表单标题 -->
      <div class="form-header">
        <i class="el-icon-edit-outline"></i>
        <span>招聘需求</span>
      </div>

      <!-- 表单内容 -->
      <el-form
        ref="demandForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
        class="demand-form"
        size="small"
      >
        <!-- 基本信息 -->
        <div class="form-section" >
          <div class="section-title">
            <i class="el-icon-info"></i>
            <span>基本信息</span>
          </div>
          <el-row :gutter="20" class="form-base-row">
            <el-col :span="8">
              <el-form-item label="需求类型" prop="require">
                <el-select 
                  v-model="formData.require" 
                  placeholder="请选择需求类型"
                >
                  <el-option
                    v-for="item in requireOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <i :class="item.icon"></i>
                    <span>{{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="需求等级" prop="level">
                <el-select 
                  v-model="formData.level" 
                  placeholder="请选择需求等级"
                >
                  <el-option
                    v-for="item in levelOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <el-tag 
                      :type="item.tagType" 
                      size="small"
                    >{{ item.label }}</el-tag>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="负责HR" prop="hr">
                <el-input 
                  v-model="formData.hr" 
                  disabled
                  placeholder="自动分配"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="提交人" prop="recruiter">
                <el-input 
                  v-model="formData.name" 
                  placeholder="自动获取"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所在部门" prop="department">
                <el-input 
                  v-model="formData.currentDepartment" 
                  disabled
                  placeholder="自动获取"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所在岗位" prop="currentStation">
                <el-input 
                  v-model="formData.currentStation" 
                  disabled
                  placeholder="自动获取"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="招聘负责人" prop="recruiter">
                <department-staff-selector
                  v-model="formData.recruiterObj"
                  @change="handleRecruiterChange"
                  placeholder="请选择招聘负责人"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="复试负责人" prop="interviewer">
                <department-staff-selector
                  v-model="formData.interviewerObj"
                  @change="handleInterviewerChange"
                  placeholder="请选择复试负责人"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="期望到岗" prop="expectedTime">
                <el-date-picker
                  v-model="formData.expectedTime"
                  type="date"
                  placeholder="选择期望到岗时间"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 岗位信息 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-office-building"></i>
            <span>岗位信息</span>
          </div>
          <el-row >
            <el-col :span="8">
              <el-form-item label="需求岗位" prop="station">
                <department-station-selector
                  v-model="formData.stationId"
                  @change="handleStationChange"
                  placeholder="请选择需求岗位"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工作地点" prop="duty">
                <el-input 
                  v-model="formData.duty" 
                  placeholder="请输入工作地点"
                  prefix-icon="el-icon-location"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="需求人数" prop="number">
                <el-input-number 
                  v-model="formData.number" 
                  :min="1" 
                  controls-position="right"
                  placeholder="请输入人数"
                ></el-input-number>
                <span class="unit">人</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="任职要求" prop="job">
                <el-input
                  type="textarea"
                  v-model="formData.job"
                  :rows="3"
                  placeholder="请输入任职要求"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row >
            <el-col :span="8">
              <el-form-item label="学历要求" prop="education">
                <el-input 
                  v-model="formData.education" 
                  placeholder="请输入学历要求"
                  prefix-icon="el-icon-reading"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="资历要求" prop="qualification">
                <el-input 
                  v-model="formData.qualification" 
                  placeholder="请输入资历要求"
                  prefix-icon="el-icon-medal"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="专业要求" prop="major">
                <el-input 
                  v-model="formData.major" 
                  placeholder="请输入专业要求"
                  prefix-icon="el-icon-notebook-2"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="性别要求" prop="gender">
                <el-select 
                  v-model="formData.gender" 
                  placeholder="请选择性别要求"
                >
                  <el-option
                    v-for="item in genderOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="年龄要求" prop="age">
                <el-input 
                  v-model="formData.age" 
                  placeholder="如：25-35岁"
                  prefix-icon="el-icon-user"
                ></el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="技能要求" prop="skills">
                <el-input
                  type="textarea"
                  v-model="formData.skills"
                  :rows="3"
                  style="width: 100% !important;"
                  placeholder="请输入技能要求"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="其他要求" prop="otherRequirements">
                <el-input
                  type="textarea"
                  v-model="formData.otherRequirements"
                  :rows="3"
                  placeholder="请输入其他要求"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 薪资信息 -->
        <div class="form-section">
          <div class="section-title">
            <i class="el-icon-money"></i>
            <span>薪资建议</span>
          </div>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="试用期工资" prop="probationSalary">
                <el-input 
                  v-model="formData.probationSalary" 
                  placeholder="请输入试用期工资"
                  prefix-icon="el-icon-coin"
                >
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="试用期限" prop="probationPeriod">
                <el-input-number
                  v-model="formData.probationPeriod"
                  :min="1"
                  :max="12"
                  controls-position="right"
                ></el-input-number>
                <span class="unit">月</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同期工资" prop="contractSalary">
                <el-input 
                  v-model="formData.contractSalary" 
                  placeholder="请输入合同期工资"
                  prefix-icon="el-icon-coin"
                >
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row >
            <el-col :span="8">
              <el-form-item label="合同期限" prop="contractPeriod">
                <el-input-number
                  v-model="formData.contractPeriod"
                  :min="1"
                  :max="10"
                  controls-position="right"
                ></el-input-number>
                <span class="unit">年</span>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="其他说明" prop="other">
                <el-input 
                  v-model="formData.other" 
                  placeholder="请输入其他薪资说明"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 表单底部按钮 -->
        <div class="form-footer">
          <el-button 
            plain
            icon="el-icon-tickets"
            @click="saveDraft"
          >保存草稿</el-button>
          <el-button 
            type="primary" 
            icon="el-icon-check"
            @click="submitForm"
          >提交需求</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>

import DepartmentStationSelector from '@/components/common/DepartmentStationSelector.vue'
import DepartmentStaffSelector from '@/components/common/DepartmentStaffSelector.vue'

export default {
  name: 'AddDemand',
  components: {
    DepartmentStationSelector,
    DepartmentStaffSelector
  },
  data() {
    return {
      formData: {
        name: '', // 提交人姓名
        require: '', // 需求类型
        level: '', // 需求等级
        hr: '', // 负责HR
        stationId: '', // 岗位ID
        station: '', // 岗位名称
        duty: '', // 工作地点
        number: 1, // 需求人数
        job: '', // 任职要求
        education: '', // 学历要求
        qualification: '', // 资历要求
        probationSalary: '', // 试用期工资
        probationPeriod: 3, // 试用期限
        contractSalary: '', // 合同期工资
        contractPeriod: 3, // 合同期限
        other: '', // 其他说明
        gender: '', // 性别要求
        age: '', // 年龄要求
        major: '', // 专业要求
        skills: '', // 技能要求
        otherRequirements: '', // 其他要求
        recruiter: '', // 招聘负责人
        interviewer: '', // 复试负责人
        expectedTime: '', // 期望到岗时间
        recruiterObj: null, // 招聘负责人对象
        interviewerObj: null, // 复试负责人对象
        department: '', // 所在部门
        departmentId: '', // 所在部门ID
        currentStation: '', // 所在岗位
        currentDepartment: ''
      },
      // 需求类型选项
      requireOptions: [
        { value: '1', label: '离职补充', icon: 'el-icon-user-solid' },
        { value: '2', label: '调动补充', icon: 'el-icon-refresh' },
        { value: '3', label: '人员储备', icon: 'el-icon-coordinate' },
        { value: '4', label: '岗位扩编', icon: 'el-icon-plus' },
        { value: '5', label: '临时用工', icon: 'el-icon-time' }
      ],
      // 需求等级选项
      levelOptions: [
        { value: '1', label: '紧急', tagType: 'danger' },
        { value: '2', label: '一般紧急', tagType: 'warning' },
        { value: '3', label: '非紧急', tagType: 'info' }
      ],
      // 添加性别选项数组
      genderOptions: [
        { value: '0', label: '不限' },
        { value: '1', label: '男' },
        { value: '2', label: '女' }
      ],
      // 日期选择器配置
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
        }
      },
      rules: {
        require: [{ required: true, message: '请选择需求类型', trigger: 'change' }],
        level: [{ required: true, message: '请选择需求等级', trigger: 'change' }],
        station: [{ required: true, message: '请选择需求岗位', trigger: 'change' }],
        duty: [{ required: true, message: '请输入工作地点', trigger: 'blur' }],
        number: [{ required: true, message: '请输入需求人数', trigger: 'blur' }],
        job: [{ required: true, message: '请输入任职要求', trigger: 'blur' }],
        gender: [{ required: true, message: '请输入性别要求', trigger: 'blur' }],
        education: [{ required: true, message: '请输入学历要求', trigger: 'blur' }],
        qualification: [{ required: true, message: '请输入资历要求', trigger: 'blur' }],
        probationSalary: [{ required: true, message: '请输入试用期工资', trigger: 'blur' }],
        probationPeriod: [{ required: true, message: '请输入试用期限', trigger: 'blur' }],
        contractSalary: [{ required: true, message: '请输入合同期工资', trigger: 'blur' }],
        contractPeriod: [{ required: true, message: '请输入合同期限', trigger: 'blur' }],
        expectedTime: [
          { required: true, message: '请选择期望到岗时间', trigger: 'change' }
        ],
      }
    }
  },
  created() {

    // 获取当前用户信息
    this.fetchCurrentUserInfo()
  },
  methods: {
    // 获取当前用户信息
    async fetchCurrentUserInfo() {
      try {

        const userData = window.sessionStorage.getItem("userInfo");
        const userInfo = JSON.parse(userData)
        this.formData.name = userInfo.username
        this.formData.currentDepartment = userInfo.department,
        this.formData.currentStation = userInfo.position
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    },
    handleStationChange(selectionResult) {
      console.log('选中的岗位信息:', selectionResult)
      this.formData.stationId = selectionResult.station.id
      this.formData.station = selectionResult.station.name
      this.formData.department =selectionResult.department.name
      this.formData.departmentId = selectionResult.department.id
    },
    // 处理招聘负责人选择
    handleRecruiterChange(staff) {
      console.log('选中的招聘负责人:', staff)
      this.formData.interviewerId = staff.staffId
      this.formData.interviewer = staff.staffName
    },
    // 处理复试负责人选择
    handleInterviewerChange(staff) {
      console.log('选中的复试负责人:', staff)
      this.formData.reInterviewerId = staff.staffId
      this.formData.reInterviewer = staff.staffName
    },
    // 保存草稿
    async saveDraft() {
      await this.saveForm(0)
    },
    // 提交表单
    async submitForm() {
      await this.saveForm(1)
    },
    // 统一的表单提交方法
    async saveForm(node) {
      this.$refs.demandForm.validate(async (valid) => {
        if (valid) {
          try {
            console.log("id"+this.formData.stationId);
            const date = new Date();

            // 构建 RecruitVO 数据结构
            const recruitVO = {
              id: null,
              proInsId: null,
              name: this.formData.name,
              requirement: parseInt(this.formData.require),
              level:parseInt(this.formData.level),
              hr: this.formData.hr || null, // 如果为空字符串则设为null
              node: node,
              expectedTime: date.toISOString().replace('T', ' ').substring(0, 19),
              state: 0,
              currentDepartment: this.formData.currentDepartment,
              currentStation: this.formData.currentStation,
              recruitDetail: {
                recruitId: null,
                stationId: this.formData.stationId, // 确保是数字
                station: this.formData.station,
                duty: this.formData.duty,
                number: parseInt(this.formData.number), // 确保是数字
                job: this.formData.job,
                education: this.formData.education,
                qualification: this.formData.qualification,
                gender: parseInt(this.formData.gender), // 确保是数字
                age: this.formData.age || null, // 如果为空字符串则设为null
                major: this.formData.major || null,
                skills: this.formData.skills || null,
                otherRequirements: this.formData.otherRequirements || null,
                probationSalary: parseFloat(this.formData.probationSalary), // 转换为数字
                probationPeriod: parseInt(this.formData.probationPeriod),
                contractSalary: parseFloat(this.formData.contractSalary),
                contractPeriod: parseInt(this.formData.contractPeriod),
                otherTips: this.formData.other || null,
                interviewer: this.formData.interviewer || null,
                reInterviewer: this.formData.reInterviewer || null,
                departmentId: this.formData.departmentId,
                department: this.formData.department,
              }
            }

            // 发送请求
            const response = await this.$axios.post('/recruitment/recruit', recruitVO)
            
            if (response.result === 200) {
              // 提交成功
              this.$message({
                type: 'success',
                message: node === 0 ? '草稿保存成功' : '需求提交成功'
              })

              this.$router.push('/recruitment/demands')
            } else {
              // 提交失败
              this.$message.error(response.message || '操作失败，请重试')
            }
          } catch (error) {
            console.error('提交失败:', error)
            this.$message.error(error.response.data.message || error.message || '操作失败，请重试')
          }
        } else {
          this.$message({
            type: 'warning',
            message: '请填写完整所有必填项'
          })
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
/* 全局样式 */
.el-card {
  border: none !important;
  margin-bottom: 10px;
}

.demand-container {
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.demand-card {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.form-header {
  padding: 0px 0px 20px 0px;
  margin-bottom: 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #303133;
}

.form-header i {
  margin-right: 8px;
  font-size: 20px;
  color: #409EFF;
}

.form-header span {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.demand-form {
  padding: 0 20px;
  height: calc(100vh - 200px);
  overflow-y: auto;
}

.form-section {
  margin-bottom: 20px;
}

.section-title {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.section-title i {
  font-size: 16px;
  color: #409EFF;
  margin-right: 8px;
}

.section-title span {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
}

.el-row {
  margin: 0 -10px;
  display: flex;
  flex-wrap: wrap;
}

.el-col {
  padding: 0 10px;
  margin-bottom: 12px;
  display: flex;
  justify-content: flex-start;
}

/* 调整表单项布局 */
.el-form-item {
  margin-bottom: 18px !important;
  margin-left: 0px !important;
  width: 100%;
}

/* 调整表单项标签宽度和间距 */
.el-form-item__label {
  padding-right: 12px !important;
  line-height: 32px !important;
}

/* 调整表单项内容区域的左边距 */
.el-form-item__content {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

/* 统一输入框宽度 */
.el-input,
.el-select,
.el-cascader,
.department-station-selector,
.el-date-editor.el-input {
  width: 100% !important;
  max-width: 360px !important;
}

/* 数字输入框宽度 */
.el-input-number {
  width: calc(100% - 30px) !important;
  max-width: 330px !important;
}

/* 文本域宽度 */
.el-textarea {
  width: 100% !important;
}

.el-textarea__inner {
  width: 100% !important;
}

.unit {
  margin-left: 8px;
  color: #909399;
}

.form-footer {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding: 15px 0;
  text-align: right;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}

/* 滚动条样式 */
.demand-form::-webkit-scrollbar {
  width: 6px;
}

.demand-form::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.demand-form::-webkit-scrollbar-track {
  background: #f5f7fa;
}

</style>
